package mongodb;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.ResourceBundle;

/**
 * @author cy
 */
public class PictureObtain {

    private static String path;
    private static Integer time;

    /**
     * 读取配置文件属性
     */
    static {
        try {
            ResourceBundle resource = ResourceBundle.getBundle("picture");
            path = resource.getString("path");
            time = Integer.parseInt(resource.getString("time"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Url的图片输入流
     * @param url
     * @return
     */
    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return conn.getInputStream();
            } else {
                System.err.println("连接失败!失败状态码"+conn.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重载saveData()
     * @param url
     */
    public static void saveData(String url){
        saveData(getInputStreamByGet(url),getFile(url));
    }


    /**
     * 向文件输入流，创建图片
     * @param is
     * @param file
     */
    public static void saveData(InputStream is, File file) {

        try (BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));) {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新文件名字的命名规则 时间(年月日时分秒yyyyMMddHHmmss_[1000-9999随机数].后缀)
     * 格式 20171206155009_3774.jpg
     * @param fileName
     * @return
     */
    public static String nameFormat(String fileName) {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 后缀名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        String dateName = dateFormat.format(new Date());
        Integer randomNum = new Random().nextInt(9000) + 1000;
        return dateName + "_" + randomNum + "." + fileExt;
    }

    /**
     *  删除超时的图片
     * @param fileRoot
     * @param time
     */
    public static void deletePicture(File fileRoot, Integer time) {
        String[] tempList = fileRoot.list();
        String fileRootString = fileRoot.toString();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (fileRootString.endsWith(File.separator)) {
                temp = new File(fileRootString + tempList[i]);
            } else {
                temp = new File(fileRootString + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                if (PictureObtain.checkTimeOut(time, tempList[i])) {
                    System.out.println("删除" + tempList[i]);
                    temp.delete();
                }
            }
            if (temp.isDirectory()) {
                File file = new File(fileRootString + "/" + tempList[i]);
                // 先删除文件夹里面的文件
                PictureObtain.deletePicture(file, time);
                // 再删除空文件夹
                PictureObtain.delFolder(file, time);
            }
        }
    }

    /**
     * 删除文件夹
     * @param folderPath
     * @param time
     */
    public static void delFolder(File folderPath, Integer time) {
        try {
            // 删除完里面所有内容
            PictureObtain.deletePicture(folderPath, time);
            // 删除空文件夹
            if (folderPath.delete()) {
                System.out.println("删除" + folderPath.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断时间是否超时
     * 格式 20171206155009_3774.jpg
     * @param time
     * @param fileName
     * @return
     */
    public static boolean checkTimeOut(Integer time, String fileName) {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String[] dateString = fileName.split("_");
        Date date = null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND, -time);
        Date dateBefore = calendar.getTime();
        try {
            date = dateFormat.parse(dateString[0]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null) {
            return false;
        } else {
            if (date.before(dateBefore)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 通过url获取文件对象
     * 在配置文件中配置path路径
     *  格式 http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg
     * @param url
     * @return
     */
    public static File getFile(String url){
        String[] split = url.split("\\/");
        String fileName = split[split.length - 1];
        String newFileName = PictureObtain.nameFormat(fileName);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String rootToday = path+File.separator+dateFormat.format(new Date());
        File fileTodayRoot = new File(rootToday);
        if (!fileTodayRoot.exists()) {
            fileTodayRoot.mkdirs();
        }
       return new File(rootToday, newFileName);
    }


    public static void main(String[] args) {
        String url = "http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg";
        String[] split = url.split("\\/");
        String fileName = split[split.length - 1];
        String newFileName = PictureObtain.nameFormat(fileName);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String rootToday = path + File.separator + dateFormat.format(new Date());
        File fileRoot = new File(path);
        File fileTodayRoot = new File(rootToday);
        if (!fileTodayRoot.exists()) {
            fileTodayRoot.mkdir();
        }
        File file = new File(rootToday, newFileName);
        InputStream inputStream = PictureObtain.getInputStreamByGet(url);
        PictureObtain.saveData(inputStream, file);
        PictureObtain.deletePicture(fileRoot, time);
    }

}
